<?php

namespace app\http\middleware;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Session;
use app\api\model\User as UserModel;
use app\api\model\Merchant as MerchantModel;
class authorized
{
    public function handle($request, \Closure $next)
    {
        $access_token=Request::header('token');
        if(empty($access_token)){
            return json(['msg'=>'need login','code'=>ERRNO['LoginNeed']]);
        }
        //验证token是否到期
        $data=verification($access_token);
        $userInfo=$data['data'];
        //验证是否退出登录
        $handler=Cache::store('redis')->handler();

        if($userInfo->type==config('data.role_type.user')){
            $key='USER:'.$data['iat'].':'.$userInfo->id;
            //验证是否被注销
            $status=UserModel::where(['id'=>$userInfo->id])->value('status');
            if($status==-1) return json(['msg'=>'The current account has been cancelled','code'=>ERRNO['USERCANCEL']]);
        }else{
            $key='MERCHANT:'.$data['iat'].':'.$userInfo->id;
            $status=MerchantModel::where(['id'=>$userInfo->id])->value('status');
            if($status==-1) return json(['msg'=>'The current account has been cancelled','code'=>ERRNO['USERCANCEL']]);
        }
        $exist=$handler->exists($key);
        if($exist){
            return json(['msg'=>'Need to login in again','code'=>ERRNO['LoginNeed']]);
        }

        //存储到session
        Session::set('jti',$data['jti']);
        Session::set('iat',$data['iat']);

        return $next($request);
    }
}
